package com.mingrisoft.servlet.front;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mingrisoft.Function;
import com.mingrisoft.utils.C3poUtils;

/**
 * 登录
 * Created by  Administrator on  2018/11/6
 */
@WebServlet(value = "/front/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/admin/login.jsp").forward(req, resp);
    }

    /**
     * 登录验证
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        request.setCharacterEncoding("utf-8");                             //设置编码方式为utf-8
        //处理表单，并进行异常处理

        try {
            Function Fun = new Function();
            String IP = request.getRemoteAddr();                        //得到客户端Ip地址
            String User = request.getParameter("User");                //得到登录用户名
            String Pwd = request.getParameter("Pwd");                   //得到登录密码

            HttpSession session = request.getSession();

            if (LoginCheck(User,Pwd)) {
                session.setAttribute("Login", "Yes");
                session.setAttribute("AdminName", User);
                //重定向后台首页
                response.sendRedirect(request.getContextPath() + "/admin/news");
                return;
            } else {
                request.setAttribute("errmsg", "用户名或密码出错");
                request.getRequestDispatcher("/WEB-INF/admin/login.jsp").forward(request, response);
            }
        } catch (Exception e) {
            request.setAttribute("errmsg", "内部出错");
            request.getRequestDispatcher("/WEB-INF/admin/login.jsp").forward(request, response);
        }

    }

    private boolean LoginCheck(String username, String password) {

        if (username == null && "".equals(username) && password == null && "".equals(password)) {
            return false;
        }

        String sql = "select * from admin where AdminName=?";

        List<Map<String,Object>> users = C3poUtils.getList(sql,username);

        if(users.size() == 0){
            return false;
        }
        //取password
        if(!password.equals(users.get(0).get("AdminPwd"))){
            return false;
        }

        return true;
    }
}
